package cn.htcode.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author: Mr_he
 * @Version:1.0
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //通过Request强转获取session，判断用户是否已经登录
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        Object user = req.getSession().getAttribute("user");
        //获取请求路径
        String requestURI = req.getRequestURI();
        //不需要拦截的路径
        String[] urls = {"/login", "/register", "/login.html", "/register.html", "/js", "/element-ui"};
        for (String URL : urls) {
            if (URL.equals(requestURI)) {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }

        if (user == null) {
            //没有登录，就只能看到登录页面
            req.getRequestDispatcher("/login.html").forward(servletRequest, servletResponse);
        } else {//放行
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
